/**
 * 
 */
package com.qq.spirit;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.qq.spirit.inter.AbstractActionAfterHttpRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlDataUtil;
import com.qq.spirit.model.XmlNodeData;

/**
 * 战役
 * 
 * @author beedoorwei
 * 
 */
public class CampaignTask implements Runnable
{

	@Override
	public void run()
	{
		try
		{
			Iterator<String> ite = UserCache.userQueue.keySet().iterator();
			while (ite.hasNext())
			{
				String username = ite.next();
				if (isCanCampaignAttack(username))
				{
					TaskManager.addTask(new Campaign(username), GameUtil.randomInt(10));
				}
			}
		} catch (Exception e)
		{
			LoggerUtil.error(e);
		}
	}

	/**
	 * 获得下次可攻击的时间
	 * 
	 * @return
	 */
	private int getNextAttackTime(String username)
	{
		int attackTime = 0;
		String tokencd = XmlDataUtil.getNodeData(UserCache.get(username).getAllPlayInfo(), "results.player.tokencd");
		int nextattack = GameUtil.convertInt(tokencd);
		if (nextattack >= (25 * 60 * 1000))
		{
			// 休息5分钟
			attackTime = 5 * 60;
		}
		return 0;
		// return attackTime;
	}

	/**
	 * 判断是否可以攻击
	 * 
	 * @param CampaignInfo
	 * @return
	 */
	private boolean isCanCampaignAttack(String username)
	{
		// 判断能够发动攻击的最快时间
		int nextAttackTime = getNextAttackTime(username);
		if (nextAttackTime > 0)
		{
			TaskManager.addTask(new Campaign(username), nextAttackTime);
			return false;
		}
		String times = XmlDataUtil.getNodeData(UserCache.get(username).getAllPlayInfo(), "results.player.token");
		if (GameUtil.convertInt(times) >= 0)
		{
			return true;
		}
		return false;
	}

	/**
	 * 战役征战
	 * 
	 * @author Administrator
	 * 
	 */
	class Campaign extends TaskUnit
	{
		public Campaign(String username)
		{
			this.username = username;
		}

		public void doTask()
		{
			try
			{
				UserData u = UserCache.get(username);
				if (u.getUserState() == UserState.LOGIN_GAME)
				{
					List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
					// 目前默认蒙古战役
					nvpList.add(new NameValuePair("armiesId", "900023"));
					HttpUtil.doPost(username, GameConstants.CAMPAIGN_TEAM_INFO_URL, nvpList, new PreCampaignAction(username));
				} else
				{
					// 添加登录任务先
					TaskManager.addTask(new LoginTask(username, this));
				}
			} catch (Exception e)
			{
				LoggerUtil.error(e);
			}
		}
	}

	/**
	 * 征战前查询
	 * 
	 * @author Administrator
	 * 
	 */
	class PreCampaignAction extends AbstractActionAfterHttpRequest
	{
		public PreCampaignAction(String username)
		{
			super();
			this.username = username;
			this.taskUnit = new Campaign(username);
		}

		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData CampaignInfo)
		{
			int needToken = GameUtil.convertInt(XmlDataUtil.getNodeData(CampaignInfo, "results.campaigndto.token"));
			if (needToken <= 4)
			{
				// 看看当前军令是否满足条件以及当前cd是否满足条件
				String tokencd = XmlDataUtil.getNodeData(UserCache.get(username).getAllPlayInfo(), "results.player.tokencd");
				if (GameUtil.convertInt(tokencd) < 25)
				{
					int hasToken = GameUtil.convertInt(XmlDataUtil.getNodeData(UserCache.get(username).getAllPlayInfo(), "results.player.token"));
					if (needToken <= hasToken)
					{
						doCampaign(CampaignInfo);
					} else
					{
						int minute = Calendar.getInstance().get(Calendar.MINUTE);
						int waitCd = 0;
						if (minute < 30)
						{
							waitCd = 30 - minute;
						} else
						{
							waitCd = 60 - minute;
						}
						// 半个小时后会自动加令
						TaskManager.addTask(new Campaign(username), (waitCd + 1) * 60);
					}
				} else
				{
					TaskManager.addTask(new Campaign(username), 5 * 60);
				}
			}
		}

		/**
		 * 获取本国组队
		 * 
		 * @param CampaignInfo
		 * @return
		 */
		private List<XmlNodeData> searchNationTeam(XmlNodeData CampaignInfo)
		{
			UserData u = UserCache.get(username);
			String usernation = GameUtil.getNation(XmlDataUtil.getNodeData(u.getAllPlayInfo(), "results.player.nation"));
			List<XmlNodeData> tempNode = XmlDataUtil.getNodeInfoList(CampaignInfo, "results.team.condition");
			List<XmlNodeData> nationTeamList = new ArrayList<XmlNodeData>();
			if (!tempNode.isEmpty())
			{
				// 不为空，有组队，查查是否有本国籍的队伍
				for (XmlNodeData cn : tempNode)
				{
					if (cn.getNodeValue().indexOf(usernation) >= 0)
					{
						nationTeamList.add(cn.getParent());
					}
				}
			}
			return nationTeamList;
		}

		/**
		 * 判断是否为队长
		 * 
		 * @param nationTeamList
		 * @return
		 */
		private boolean isTeamLeader(List<XmlNodeData> nationTeamList)
		{
			for (XmlNodeData xm : nationTeamList)
			{
				String teamname = XmlDataUtil.getNodeData(xm, "teamname");
				if (teamname.equals(UserCache.getGameName(username)))
				{
					return true;
				}
			}
			return false;
		}

		/**
		 * 是否在组队中
		 * 
		 * @param CampaignInfo
		 * @return
		 */
		private boolean isInTeam(XmlNodeData CampaignInfo)
		{
			List<XmlNodeData> tempNode = XmlDataUtil.getNodeInfoList(CampaignInfo, "results.member.playername");
			for (XmlNodeData xm : tempNode)
			{
				if (xm.getNodeValue().equals(UserCache.getGameName(username)))
				{
					return true;
				}
			}

			return false;
		}

		/**
		 * @param CampaignInfo
		 * @return
		 */
		private int getTeamCurrNum(List<XmlNodeData> nationTeamList)
		{
			for (XmlNodeData xm : nationTeamList)
			{
				String teamname = XmlDataUtil.getNodeData(xm, "teamname");
				if (teamname.equals(UserCache.getGameName(username)))
				{
					return GameUtil.convertInt(XmlDataUtil.getNodeData(xm, "currentnum"));
				}
			}
			return 0;
		}

		/**
		 * 开始战役
		 */
		private void doCampaign(XmlNodeData CampaignInfo)
		{
			List<XmlNodeData> nationTeamList = searchNationTeam(CampaignInfo);
			if (nationTeamList.isEmpty())
			{
				LoggerUtil.logger(UserCache.getGameName(username) + "没有查询到本国组队信息");
				createTeam();
			} else
			{
				// 有组队，分2步，先看看自己是否是队长，如果不是，判断是否在队伍中
				if (isTeamLeader(nationTeamList))
				{
					// 找到了，那么这个号就是队长，查看人数是否满足条件
					int currentnum = getTeamCurrNum(nationTeamList);
					if (currentnum >= 5)
					{
						// 开始吧
						HttpUtil.doGet(username, GameConstants.BATTLE_MULTI_ATTACK_URL, new CampaignAttackAction(username));
					} else
					{
						// 继续等待，5秒钟后继续看
						TaskManager.addTask(new Campaign(username), GameUtil.randomInt(10));
					}
				} else
				{
					// 没找到，看看自己是否是队员
					if (isInTeam(CampaignInfo))
					{
						// 等待5秒钟后再看下组队信息
						TaskManager.addTask(new Campaign(username), 5);
					} else
					{
						joinOrCreateTeam(nationTeamList);
					}
				}
			}
		}

		/**
		 * 开启加入组队/创建组队功能，优先加入组队，如果没队伍可以加，那么就创建组队
		 */
		private void joinOrCreateTeam(List<XmlNodeData> nationTeamList)
		{
			XmlNodeData tp = null;
			Iterator<XmlNodeData> teamIte = nationTeamList.iterator();
			while (teamIte.hasNext())
			{
				tp = teamIte.next();
				int currentnum = GameUtil.convertInt(XmlDataUtil.getNodeData(tp, "currentnum"));
				if (currentnum < 8)
				{
					teamIte.remove();
					break;
				}
			}
			if (tp != null)
			{
				// 找到了小于8个人的组队
				List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
				nvpList.add(new NameValuePair("teamId", XmlDataUtil.getNodeData(tp, "teamid")));
				HttpUtil.doPost(username, GameConstants.BATTLE_MULTI_JOIN_TEAM_URL, nvpList, new CampaignJoinTeamAction(username, nationTeamList));
			} else
			{
				createTeam();
			}
		}

		/**
		 * 创建组队
		 */
		private void createTeam()
		{
			List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
			nvpList.add(new NameValuePair("campaignId", "18"));
			nvpList.add(new NameValuePair("rule", "4:0;2"));
			HttpUtil.doPost(username, GameConstants.CAMPAIGN_CREATE_TEAM_URL, nvpList, new CampaignTeamAction(username));
		}

	}

	/**
	 * 发起攻击事后处理对象
	 * 
	 * @author Administrator
	 * 
	 */
	class CampaignAttackAction extends AbstractActionAfterHttpRequest
	{
		public CampaignAttackAction(String username)
		{
			super();
			this.username = username;
		}

		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData CampaignAttackInfo)
		{
			// 获取攻击结果
			String describe = XmlDataUtil.getNodeData(CampaignAttackInfo, "results.sceneevent.battlereport.report.describe");
			String gains = XmlDataUtil.getNodeData(CampaignAttackInfo, "results.sceneevent.battlereport.report.gains");
			LoggerUtil.info("攻击战役:" + describe + "," + GameUtil.getStr(gains));

			updatePlayerbattleinfo(username, CampaignAttackInfo);
			// 提交5秒钟后刷新
			TaskManager.addTask(new Campaign(username), GameUtil.randomInt(10));
		}
	}

	/**
	 * 创建组队回调事件
	 * 
	 * @author Administrator
	 * 
	 */
	class CampaignTeamAction extends BattleActionAfterHttpRequest
	{
		public CampaignTeamAction(String username)
		{
			super();
			this.username = username;
		}

		@Override
		public void doCall(List<NameValuePair> headerList, String content)
		{
			XmlNodeData CampaignInfo = XmlDataUtil.convertXmlToDataModel(content);
			if (GameUtil.isGameStateSuc(CampaignInfo))
			{
				TaskManager.addTask(new LoginTask(username, new Campaign(username)));
			} else
			{
				String createCampaignTeamResult = GameUtil.getResultState(CampaignInfo);
				if (createCampaignTeamResult.equals("1"))
				{
					// 创建组队成功
					LoggerUtil.info(UserCache.getGameName(username) + "创建战役组队成功");
				} else
				{
					String message = GameUtil.getResultMessage(CampaignInfo);
					// 创建组队失败
					LoggerUtil.info(UserCache.getGameName(username) + "创建战役组队失败，原因:" + message);
				}
				// 提交5秒钟后刷新任务,如果成功刷新等待开始攻击，否则重新征战任务
				TaskManager.addTask(new Campaign(username), GameUtil.randomInt(10));
			}
		}
	}

	/**
	 * 加入组队回调事件
	 * 
	 * @author Administrator
	 * 
	 */
	class CampaignJoinTeamAction extends BattleActionAfterHttpRequest
	{
		String username = null;
		List<XmlNodeData> nationTeamList = null;

		public CampaignJoinTeamAction(String username, List<XmlNodeData> nationTeamList)
		{
			super();
			this.username = username;
			this.nationTeamList = nationTeamList;
		}

		@Override
		public void doCall(List<NameValuePair> headerList, String content)
		{
			XmlNodeData CampaignInfo = XmlDataUtil.convertXmlToDataModel(content);
			if (GameUtil.isGameStateSuc(CampaignInfo))
			{
				TaskManager.addTask(new LoginTask(username, new Campaign(username)));
			} else
			{
				String createCampaignTeamResult = GameUtil.getResultState(CampaignInfo);
				if (createCampaignTeamResult.equals("1"))
				{
					// 加入组队成功
					LoggerUtil.info(username + "加入战役组队成功");
					// 提交5秒钟后刷新任务
					TaskManager.addTask(new Campaign(username), 10);
				} else
				{
					String message = GameUtil.getResultMessage(CampaignInfo);
					// 加入组队失败
					LoggerUtil.info(username + "加入战役组队失败，原因:" + message);
				}
			}
		}
	}

}
